package cn.chenhuanming.chuanzhi.service;

import cn.chenhuanming.chuanzhi.dao.ShareDao;
import cn.chenhuanming.chuanzhi.dao.StaffDao;
import cn.chenhuanming.chuanzhi.util.authority.AuthorityTool;
import cn.chenhuanming.chuanzhi.util.entity.Share;
import cn.chenhuanming.chuanzhi.util.entity.Staff;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * Created by Administrator on 2017-05-06.
 */
@Service
public class ShareService {

    @Autowired
    StaffDao staffDao;

    @Autowired
    ShareDao shareDao;

    public Page<Share> listShare(Pageable pageable){
        return shareDao.findAll(pageable);
    }

    public Page<Share> search(String keyword,Pageable pageable){
        return shareDao.findByTitleContainingOrContentContaining(keyword,keyword,pageable);
    }

    public Share findShare(String id){
        return shareDao.findOne(id);
    }

    public void newShare(Share share){
        if(share.getTitle().equals("")||share.getContent().equals(""))
            return;
        share.setDescription(getDescriptionFromContent(share.getDescription()));
        share.setPublishTime(LocalDateTime.now());
        share.setLastTime(LocalDateTime.now());
        share.setStaff(staffDao.getOne(AuthorityTool.getPrincipal()));
        shareDao.save(share);
    }

    public void delete(String shareId){
        Share share = shareDao.getOne(shareId);
        if(!share.getStaff().getUsername().equals(AuthorityTool.getPrincipal()))
            return;
        else
            shareDao.delete(share);
    }

    private String getDescriptionFromContent(String content){
        String description;
        if(content.length()<100)
            description = content.substring(0,content.length());
        else
            description = content.substring(0,100)+"   ...";
        return description;
    }
}
